<template>
  <div class="art-full-height">
    <!-- 搜索栏 -->
    <ArtSearchBar
      v-model="searchForm"
      :items="formItems"
      :show-expand="true"
      @search="handleSearch"
      @reset="handleResetSearch"
    />

    <ElCard class="art-table-card" shadow="never">
      <ArtTableHeader
        v-model:columns="columnChecks"
        v-model:showSearchBar="showSearchBar"
        :loading="loading"
        @refresh="refreshData"
      >
        <template #left>
          <ElSpace wrap>
            <ElButton type="primary" :icon="Plus" @click="handleAdd"> 新增活动任务 </ElButton>
          </ElSpace>
        </template>
      </ArtTableHeader>

      <!-- 数据表格 -->
      <ArtTable
        :loading="loading"
        :data="data"
        :columns="columns"
        :pagination="pagination"
        @pagination:size-change="handleSizeChange"
        @pagination:current-change="handleCurrentChange"
      >
        <!-- 小区图片列（仅显示第一张，若有多张则显示数量提示） -->
        <template #areaPhoto="{ row }">
          <div v-if="row.areaPhoto.length > 0" class="flex items-center gap-2">
            <ElImage
              :src="row.areaPhoto[0].url"
              :preview-src-list="row.areaPhoto.map((item: any) => item.url)"
              preview-teleported
              fit="cover"
              class="w-10 h-10"
            />
            <span v-if="row.areaPhoto.length > 1" class="text-xs text-gray-500 ml-1">
              +{{ row.areaPhoto.length - 1 }}张
            </span>
          </div>
          <span v-else class="no-image">暂无图片</span>
        </template>

        <!-- 显示状态 -->
        <template #areaUpFlag="{ row }">
          <!-- <ElTag :type="'success'"> {{ row.areaUpFlag === 1 ? '隐藏' : '显示' }} </ElTag> -->
           <ElTag :style="{ color: row.areaUpFlag === 1 ? '#fa896b' : '#13d1b9' }" :color="row.areaUpFlag === 1 ? '#fdede8' : '#e7fcf8'">
  {{ row.areaUpFlag === 1 ? '隐藏' : '显示' }}
</ElTag>
        </template>
      </ArtTable>

      <!-- 新增/编辑对话框 -->
      <actEditDialog
        v-model="editDialogVisible"
        :act-data="currentAreaData"
        @success="handleDialogSuccess"
      />
    </ElCard>
  </div>
</template>

<script setup lang="ts">
  import { ref, computed ,onMounted} from 'vue'
  import { dayjs, ElMessage, ElMessageBox } from 'element-plus'
  import { Plus } from '@element-plus/icons-vue'
  import { useTable } from '@/composables/useTable'
  import ArtSearchBar from '@/components/core/forms/art-search-bar/index.vue'
  import ArtTable from '@/components/core/tables/art-table/index.vue'
  import actEditDialog from './modules/act-edit-dialog.vue'
  import { taskInfoGetDataUsingPost, taskInfoPageDataUsingPost, GeoAreaVo,taskInfoDelDataUsingPost,apiDictListByTypeUsingPost } from '@/api'
  import ArtButtonTable from '@/components/core/forms/art-button-table/index.vue'
  import { useRouter } from 'vue-router';

  // 类型定义
  interface SearchForm {
    taskName: string,
    taskLinkUserName: string,
    taskLinkUserPhone: string,
  }

  interface ButtonMoreItem {
    key: string
    label: string
    icon?: any
    color?: string
    auth?: string
  }

  const router = useRouter();

  // 响应式数据
  const searchForm = ref<SearchForm>({
    taskName: '',
    taskLinkUserName: '',
    taskLinkUserPhone: '',
  })

  const editDialogVisible = ref(false)
  const currentAreaData = ref<GeoAreaVo | null>(null)

  // 搜索表单配置
  const formItems = computed(() => [
    {
      key: 'taskName',
      label: '活动名称',
      type: 'input',
      props: {
        placeholder: '请输入活动名称',
        clearable: true
      }
    },
    {
      key: 'taskLinkUserName',
      label: '联系用户',
      type: 'input',
      props: {
        placeholder: '请输入联系用户',
        clearable: true
      }
    },
    {
      key: 'taskLinkUserPhone',
      label: '联系电话',
      type: 'input',
      props: {
        placeholder: '请输入联系电话',
        clearable: true
      }
    }
  ])

  // 使用 useTable 管理表格数据
  const {
    columns,
    columnChecks,
    data,
    loading,
    pagination,
    getData,
    searchParams,
    resetSearchParams,
    handleSizeChange,
    handleCurrentChange,
    refreshData
  } = useTable({
    core: {
      apiFn: taskInfoPageDataUsingPost,
      apiParams: {
        body: searchForm.value
      },
      paginationWrapper: 'body', // 将分页参数包装到 body 对象中
      columnsFactory: () => [
        
        {
          prop: 'taskName',
          label: '活动名称',
          width: 150
        },
        {
          prop: 'taskArrange',
          label: '活动安排',
          width: 150
        },
        {
          prop: 'taskUpFlag',
          label: '上架状态',
          align: 'center',
          headerAlign: 'center',
          width: 150,
          formatter: (row: GeoAreaVo) => row.taskUpFlag == 1 ? '下架' : row.taskUpFlag == 2 ? '上架' : '未知'
        },
        {
          prop: 'taskHold',
          label: '举办方',
          align: 'center',
          headerAlign: 'center',
          width: 150
        },
        {
          prop: 'taskLinkUserName',
          label: '联系用户',
          align: 'center',
          headerAlign: 'center',
          width: 150
        },
        {
          prop: 'taskLinkUserPhone',
          label: '联系电话',
          align: 'center',
          headerAlign: 'center',
          width: 150
        },
        
        {
          prop: 'taskMaxPerson',
          label: '参与人数',
          align: 'center',
          headerAlign: 'center',
          width: 150
        },
        {
          prop: 'taskScore',
          label: '积分',
          align: 'center',
          headerAlign: 'center',
          width: 150
        },
        {
          prop: 'taskTimeBegin',
          label: '开始时间',
          width: 200,
          align: 'center',
          headerAlign: 'center',
          formatter: (row: GeoAreaVo) => dayjs(row.taskTimeBegin).format('YYYY-MM-DD')
        },
        {
          prop: 'taskTimeEnd',
          label: '结束时间',
          width: 200,
          align: 'center',
          headerAlign: 'center',
          formatter: (row: GeoAreaVo) => dayjs(row.taskTimeEnd).format('YYYY-MM-DD')
        },
        {
          prop: 'taskAddress',
          label: '活动地址',
          minWidth: 150,
          showOverflowTooltip: true
        },
        {
          prop: 'taskInfo',
          label: '活动介绍',
          minWidth: 150,
          showOverflowTooltip: true
        },
        
        {
          prop: 'operation',
          label: '操作',
          width: 200,
          fixed: 'right',
          align: 'center',
          headerAlign: 'center',
          formatter: (row) => {
            return h('div', {}, [
              h(ArtButtonTable, {
                type: 'view',
                onClick: () => buttonMoreClick({ key: 'view', label: '查看' }, row),
                title: '查看'
              }),
              h(ArtButtonTable, {
                type: 'edit',
                onClick: () => buttonMoreClick({ key: 'edit', label: '编辑' }, row)
              }),
              h(ArtButtonTable, {
                type: 'delete',
                onClick: () => buttonMoreClick({ key: 'delete', label: '删除' }, row)
              })
            ])
          }
        }
      ]
    },
    hooks: {
      onSuccess: (tableData: GeoAreaVo[]) => {
        data.value = tableData.map((item: GeoAreaVo) => {
          item.areaPhoto = JSON.parse(item.areaPhoto || '[]')
          return item
        })
      }
    }
  })

  const showSearchBar = ref(false)

  const handleSearch = () => {
    searchParams.body = searchForm.value
    getData()
  }
  const handleResetSearch = () => {
    searchParams.body = {}
    getData()
  }

  const handleAdd = () => {
    currentAreaData.value = null
    editDialogVisible.value = true
  }

  const buttonMoreClick = async (item: ButtonMoreItem, row: GeoAreaVo) => {
    switch (item.key) {
      case 'view':

      router.push({
         name: 'actDetail',
         query: { id: row.id }
      });
        break
      case 'edit':
        taskInfoGetDataUsingPost({
          body: {
            id: row.id
          }
        }).then((data) => {
          currentAreaData.value = data as GeoAreaVo
          editDialogVisible.value = true
        })
        break
      case 'delete':
        await handleDelete(row)
        break
    }
  }

  const handleDelete = async (row: GeoAreaVo) => {
    try {
      await ElMessageBox.confirm(`确定要删除小区"${row.taskName}"吗？`, '删除确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      // 这里应该调用删除接口，暂时用提示代替
      await taskInfoDelDataUsingPost({body: {
            id: row.id
          }})
      ElMessage.success('删除成功')
      getData()
    } catch {
      // 用户取消删除
    }
  }

  const handleDialogSuccess = () => {
    editDialogVisible.value = false
    currentAreaData.value = null
    getData()
  }

  onMounted(() => {
    getDictType()
  })


  const getDictType = async() => {
    const res = await apiDictListByTypeUsingPost({body:[1]})
  }

  
</script>

<style lang="scss" scoped>
  .services-list {
    display: flex;
    flex-wrap: wrap;
    gap: 4px;
  }

  .service-tag {
    margin: 2px;
  }

  .no-image {
    font-size: 12px;
    color: rgb(var(--art-text-gray-500));
  }

</style>
